package com.dingding.service.impl;

import com.dingding.common.ResponseCode;
import com.dingding.common.ServerResponse;
import com.dingding.dao.BookInfoMapper;
import com.dingding.dao.CategoryMapper;
import com.dingding.pojo.BookInfo;
import com.dingding.pojo.Category;
import com.dingding.service.IBookService;
import com.dingding.service.ICategoryService;
import com.dingding.util.DateTimeUtil;
import com.dingding.util.PropertiesUtil;
import com.dingding.vo.BookDetailVo;
import com.dingding.vo.BookListVo;
import com.dingding.common.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 张柏桦 on 2017/8/24.
 */

@Service("iBookService")
public class BookServiceImpl implements IBookService {

    @Autowired
    private BookInfoMapper bookInfoMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private ICategoryService iCategoryService;
    
    
    public ServerResponse saveOrUpdateBook(BookInfo bookInfo) {
        if(bookInfo != null){

            if(StringUtils.isNotBlank(bookInfo.getPictureUrl())){
                String[] subImageArray = bookInfo.getPictureUrl().split(",");
                if(subImageArray.length > 0){
                    bookInfo.setMainImage(subImageArray[0]);
                }
            }

            if(bookInfo.getId() != null){
                //通过 id 更新产品信息
                int rowCount = bookInfoMapper.updateByPrimaryKey(bookInfo);
                if(rowCount > 0){
                    return ServerResponse.createBySuccess("更新产品成功");
                }
                return ServerResponse.createByErrorMessage("更新产品失败");
            }else{
                //新增商品
                int rowCount = bookInfoMapper.insert(bookInfo);
                if(rowCount > 0){
                    return ServerResponse.createBySuccess("新增商品成功");
                }
                return ServerResponse.createByErrorMessage("新增商品失败");
            }
        }

        return ServerResponse.createByErrorMessage("新增产品参数不正确");
    }

    public ServerResponse<String> setSaleStatus(Integer bookId, Integer status) {
        if(bookId == null|| status == null){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(),ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        BookInfo bookInfo = new BookInfo();
        bookInfo.setId(bookId);
        bookInfo.setStatus(status);
        int rowCount = bookInfoMapper.updateByPrimaryKeySelective(bookInfo);
        if(rowCount > 0){
            return ServerResponse.createBySuccess("修改产品销售状态成功");
        }
        return ServerResponse.createByErrorMessage("修改产品销售状态失败");
    }

    public ServerResponse<BookDetailVo> manageBookDetail(Integer bookId) {
        if(bookId == null){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(),ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        BookInfo bookInfo = bookInfoMapper.selectByPrimaryKey(bookId);
        if(bookInfo == null){
            return ServerResponse.createByErrorMessage("产品不存在");
        }
        BookDetailVo bookDetailVo = assemblebookDetailVo(bookInfo);
        return ServerResponse.createBySuccess(bookDetailVo);
    }

    public ServerResponse<PageInfo> getBookList(int pageNum, int pageSize) {
        
        PageHelper.startPage(pageNum,pageSize);
        List<BookInfo> bookInfoList = bookInfoMapper.selectList();
        List<BookListVo> bookListVoList = Lists.newArrayList();
        for (BookInfo bookInfoItem : bookInfoList){
            BookListVo bookinfoListVo = assemblebookinfoListVo(bookInfoItem);
            bookListVoList.add(bookinfoListVo);
        }
        
        PageInfo pageResult = new PageInfo(bookListVoList);
        return ServerResponse.createBySuccess(pageResult);
    }

    public ServerResponse<PageInfo> searchBook(String bookTitle, Integer bookId, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        if(StringUtils.isNotBlank(bookTitle)){
            bookTitle = new StringBuilder().append("%").append(bookTitle).append("%").toString();
        }
        List<BookInfo> bookInfoList = bookInfoMapper.selectByNameAndBookId(bookTitle,bookId);
        List<BookListVo> bookListVoList = Lists.newArrayList();
        for (BookInfo bookinfoItem : bookInfoList){
            BookListVo bookListVo = assemblebookinfoListVo(bookinfoItem);
            bookListVoList.add(bookListVo);
        }
        PageInfo pageResult = new PageInfo(bookInfoList);
        pageResult.setList(bookListVoList);
        return ServerResponse.createBySuccess(pageResult);
    }

    private BookListVo assemblebookinfoListVo(BookInfo bookInfo){
        BookListVo bookListVo = new BookListVo();
        bookListVo.setId(bookInfo.getId());
        bookListVo.setBookTitle(bookInfo.getTitle());
        bookListVo.setCategoryId(bookInfo.getCategoryiesId());
        bookListVo.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix"));
        bookListVo.setMainImage(bookInfo.getMainImage());
        bookListVo.setPrice(bookInfo.getPrice());
        bookListVo.setIntroduce(bookInfo.getIntroduce());
        bookListVo.setStatus(bookInfo.getStatus());

        return bookListVo;
    }

    private BookDetailVo assemblebookDetailVo(BookInfo bookInfo){

        BookDetailVo bookDetailVo = new BookDetailVo();
        bookDetailVo.setId(bookInfo.getId());
        bookDetailVo.setIntroduce(bookInfo.getIntroduce());
        bookDetailVo.setPrice(bookInfo.getPrice());
        bookDetailVo.setMainImage(bookInfo.getMainImage());
        bookDetailVo.setPictureUrl(bookInfo.getPictureUrl());
        bookDetailVo.setCategoryId(bookInfo.getCategoryiesId());
        bookDetailVo.setDetail(bookInfo.getDetail());
        bookDetailVo.setBookTitle(bookInfo.getTitle());
        bookDetailVo.setStatus(bookInfo.getStatus());
        bookDetailVo.setStock(bookInfo.getStock());

        bookDetailVo.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix","http://img.happymmall.com/"));
        Category category = categoryMapper.selectByPrimaryKey(bookInfo.getCategoryiesId());
        if(category == null){
            bookDetailVo.setParentCategoryId(0);//默认根节点
        }else {
            bookDetailVo.setParentCategoryId(category.getId());
        }
        bookDetailVo.setCreateTime(DateTimeUtil.dateToStr(bookInfo.getCreateTime()));
        bookDetailVo.setUpdateTime(DateTimeUtil.dateToStr(bookInfo.getUpdateTime()));

        return bookDetailVo;
    }

    public ServerResponse<BookDetailVo> getBookDetail(Integer bookId){
        if(bookId == null){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(),ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        BookInfo bookInfo = bookInfoMapper.selectByPrimaryKey(bookId);
        if(bookInfo == null){
            return ServerResponse.createByErrorMessage("该书不存在");
        }
        if(bookInfo.getStatus() != Const.BookStatusEnum.ON_SELL.getCode()){
            return ServerResponse.createByErrorMessage("该书已下架或删除");
        }
        BookDetailVo bookDetailVo = assemblebookDetailVo(bookInfo);
        return ServerResponse.createBySuccess(bookDetailVo);
    }

    public ServerResponse<PageInfo> getBookByKeywordCategory(String keyword,Integer categoryId,int pageNum,int pageSize,String orderBy){
        if(StringUtils.isBlank(keyword) && categoryId == null){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(),ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        List<Integer> categoryIdList = new ArrayList<Integer>();

        if(categoryId != null){
            Category category = categoryMapper.selectByPrimaryKey(categoryId);
            if(category == null && StringUtils.isBlank(keyword)){
                //没有该分类,并且还没有关键字,这个时候返回一个空的结果集,不报错
                PageHelper.startPage(pageNum,pageSize);
                List<BookListVo> bookListVoList = Lists.newArrayList();
                PageInfo pageInfo = new PageInfo(bookListVoList);
                return ServerResponse.createBySuccess(pageInfo);
            }
            if(category != null) {
                categoryIdList = iCategoryService.selectCategoryAndChildrenById(category.getId()).getData();
            }
        }
        if(StringUtils.isNotBlank(keyword)){
            keyword = new StringBuilder().append("%").append(keyword).append("%").toString();
        }

        PageHelper.startPage(pageNum,pageSize);
        //排序处理
        if(StringUtils.isNotBlank(orderBy)){
            if(Const.bookListOrderBy.PRICE_ASC_DESC.contains(orderBy)){
                String[] orderByArray = orderBy.split("_");
                PageHelper.orderBy(orderByArray[0]+" "+orderByArray[1]);
            }
        }
        List<BookInfo> bookInfoList = bookInfoMapper.selectByNameAndCategoryIds(StringUtils.isBlank(keyword)?null:keyword,categoryIdList.size()==0?null:categoryIdList);

        List<BookListVo> productListVoList = Lists.newArrayList();
        for(BookInfo bookInfo : bookInfoList){
            BookListVo bookListVo = assemblebookinfoListVo(bookInfo);
            productListVoList.add(bookListVo);
        }

        PageInfo pageInfo = new PageInfo(bookInfoList);
        pageInfo.setList(productListVoList);
        return ServerResponse.createBySuccess(pageInfo);
    }
}
